//
//  GMDownloader.m
//  gentleman
//
//  Created by 范月成 on 2017/12/20.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMDownloader.h"
#import "GMFileManager.h"
#import "GMArtworkItem.h"
#import "VendorHeader.h"


@interface GMDownloader ()

@property (nonatomic, assign) NSInteger failureCount;
@property (nonatomic, assign) NSInteger receivedCount;
@property (nonatomic, strong) GMArtwork *artwork;

@end

@implementation GMDownloader

+ (instancetype)downloader {
    return [[[self class] alloc] init];
}

+ (instancetype)defaultDownloader {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [self downloader];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
  
    return self;
}

- (void)downloadArtworksWithArtwork:(GMArtwork *)artwork
                            gallery:(GMGallery *)gallery
                           progress:(downloaderProgressBlock)progress
                          completed:(downloaderCompletedBlock)completed {
    self.receivedCount = 0;
    self.failureCount = 0;
 
    GMArtwork *art = [GMArtwork objectForId:@(artwork.gid)];
    if (art) {
        self.artwork = art;
    } else {
        self.artwork = artwork;
    }
    
    [GMArtworkItem getArtworksWithUrl:artwork.url gid:artwork.gid showkey:gallery.showkey totalPage:artwork.filecount completed:^(NSMutableArray *artworks) {
        
        if (artworks.count) {
            !artworks.count?:[self startDownloadArtworks:artworks progress:progress completed:completed];
        } else {
            completed([NSError errorWithDomain:@"下载失败，无数据" code:444 userInfo:nil], 0, artworks.count);
        }
    }];
}

- (void)startDownloadArtworks:(NSArray *)artworks
                     progress:(downloaderProgressBlock)progress
                    completed:(downloaderCompletedBlock)completed {
    self.artwork.isDownload = YES;
    [self.artwork save];
    
    for (NSInteger i = 0; i<artworks.count; i++) {
        GMArtworkItem *item = artworks[i];
        item.gid = self.artwork.gid;
        [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
            request.url = item.imagePageUrl;
            request.httpMethod = kXMHTTPMethodGET;
            request.responseSerializerType = kXMResponseSerializerRAW;
        } onSuccess:^(id  _Nullable responseObject) {
            
            TFHpple *parser = [[TFHpple alloc] initWithHTMLData:responseObject];
            NSArray *elements = [parser searchWithXPathQuery:@"//div[@id='i3']//a//img"];
            TFHppleElement *element = elements.firstObject;
            NSString *imgUrl = element.attributes[@"src"];
            item.imageUrl = imgUrl;
            if (!imgUrl) {
                self.failureCount ++;
            } else {
                self.receivedCount ++;
            }
            [item save];
            !progress?:progress(self.receivedCount, artworks.count);
            if (self.receivedCount + self.failureCount == artworks.count) {
                !completed?:completed(nil, self.receivedCount, artworks.count);
                [self downloadImages:artworks];
            }
        } onFailure:^(NSError * _Nullable error) {
            self.failureCount ++;
            if (self.receivedCount + self.failureCount == artworks.count) {
                !completed?:completed(nil, self.receivedCount, artworks.count);
                [self downloadImages:artworks];
            }
        }];
    }
}

- (void)downloadImages:(NSArray *)artworks {
    
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableArray *urls = @[].mutableCopy;
        for (GMArtworkItem *item in artworks) {
            [urls addObject:[NSURL URLWithString:item.imageUrl]];
        }
        [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:urls];
    });
}

@end
